from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import re,redis,json
# Create your views here.



#登录
class Deng(APIView):
    def post(self,request):
        mobile=request.data.get('mobile')
        cs=request.data.get('cs')
        try:
            Lu.objects.get(mobile=mobile)
        except:
            return Response({'code':204,'msg':'手机号错误'})

        cls = redis.Redis(host='localhost', port=6379, db=4,)
        rds_data = cls.get(mobile)
        if rds_data:
            r_code = rds_data.decode()
        else:
            return Response({'code': 200, 'msg': '登录成功'})
        if cs != r_code:
            return Response({'code': 406, 'msg': '验证码错误'})
        return Response({'code': 405, "msg": '短信验证码已过期'})


class Deng1(APIView):
    def post(self,request):
            name = request.data.get('name')
            password = request.data.get('password')
            try:
                user = Lu.objects.get(name=name)
            except:
                return Response({'code': 401, 'msg': '用户名不存在'})
            if user.password != password:
                return Response({'code': 402, 'msg': '密码错误'})
            return Response({'code': 200, 'msg': '登录成功'})


#验证码
from users.stuse import send_message
class Yan(APIView):
    def get(self, request):
        mobile = request.query_params.get('mobile')
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return Response({'code': 205, 'msg': '手机号不正确'})
        resp = send_message(mobile)  # 。。。。。。。。。
        if json.loads(resp)['statusCode'] == '112310' or json.loads(resp)['statusCode'] == '000000':
            return Response({'msg': '验证码发送成功', 'code': 200})
        else:
            return Response({'msg': '验证码发送失败', 'code': 206})


#关注
class Shou(APIView):
    def get(self,request):
        set=Wo.objects.filter(hu=0)
        list=[]
        for i in set:
            list.append({
                'id':i.id,
                'name':i.name,
                'img':i.img,
                'hu':i.hu
            })
        return Response(list)

#粉丝
class Fen(APIView):
    def get(self, request):
        set = Wo.objects.filter(hu=2)
        list = []
        for i in set:
            list.append({
                'id': i.id,
                'name': i.name,
                'img': i.img,
                'hu': i.hu
            })
        return Response(list)

class Fe(APIView):
    def get(self, request):
        set = Wo.objects.filter(hu=1)
        list = []
        for i in set:
            list.append({
                'id': i.id,
                'name': i.name,
                'img': i.img,
                'hu': i.hu
            })
        return Response(list)